import re
import time
from flask import request
from flask_restful import abort
from flask_login import current_user, login_user
from funcy import project
from sqlalchemy.orm.exc import NoResultFound
from sqlalchemy.exc import IntegrityError
from funcy import partial

from redash import models, limiter
from redash.permissions import (
    require_permission,
    require_admin_or_owner,
    is_admin_or_owner,
    require_permission_or_owner,
    require_admin_default,
)
from redash.handlers.base import (
    BaseResource,
    require_fields,
    get_object_or_404,
    paginate,
    order_results as _order_results,
)

from redash.authentication.account import (
    invite_link_for_user,
    send_invite_email,
    send_password_reset_email,
    send_verify_email,
)
from redash.settings import parse_boolean
from redash import settings


class TimeSerialListResource(BaseResource):
    def get(self,parent_id,timestruct_id):
      results = models.TimeSerial.get_by_parent_id(parent_id,timestruct_id,self.current_org).order_by(models.TimeSerial.num.asc())
      return [t.to_dict() for t in results]

class TimeSerialsResource(BaseResource):
    @require_admin_default
    def post(self):
        req = request.get_json(force=True)
        require_fields(req, ("num","name"))

        timeserial = models.TimeSerial(
            num=req["num"],
            org=self.current_org,
            name=req["name"],
            calendar_enum=req["calendar_enum"],
            timestruct_id=req["timestruct_id"],
            parent_id=req["parent_id"],
            begin_date=req["begin_date"],
            close_date=req["close_date"],
            timeserialstatus_enum='draft',
        )

        try:
            models.db.session.add(timeserial)
            models.db.session.commit()
        except IntegrityError as e:
            if "num" in str(e):
                abort(400, message="编号已存在.")
            abort(500)

        timeserial.record_event(
            {"action": "create", "object_id": timeserial.id, "object_type": "timeserial"}
        )


class TimeSerialResource(BaseResource):
    def get(self, timeserial_id):
        result = models.TimeSerial.get_by_id(timeserial_id)
        return result.to_dict()

    @require_admin_default
    def post(self, timeserial_id):
        req = request.get_json(force=True)
        require_fields(req, ("num","name"))

        timeserial = models.TimeSerial.get_by_id(timeserial_id)
        params = dict(num=req["num"], name=req["name"])
        try:
            self.update_model(timeserial, params)
            models.db.session.commit()
        except IntegrityError as e:
            if "num" in str(e):
                abort(400, message="编号已存在.")
            abort(500)

    @require_admin_default
    def delete(self, timeserial_id):
        timeserial =  models.TimeSerial.get_by_id(timeserial_id)
        models.db.session.delete(timeserial)
        models.db.session.commit()


class TimeSerialTree(BaseResource):
    def get(self, timeserialstatus_enum):
        result =models.TimeSerial.get_timeserialtree(timeserialstatus_enum,self.current_org.id)
        return result[0]
